﻿#include "dialog_log.h"
#include "ui_dialog_log.h"

Dialog_log::Dialog_log(Controller *mc, QWidget *parent):
    QDialog(parent),
    ui (new Ui::Dialog_log),
    mc (mc)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); //去掉右上角的？号
    this->setWindowTitle(QString::fromUtf8("调试信息"));
    logs.clear();
    auto_scroll = true;
    ui->checkBox->setChecked(true);
    connect(mc, &Controller::log_data_recved, this, &Dialog_log::log_data_recved);
}

void Dialog_log::log_data_recved(int src, int dest, QString text){
    QString d = logs[src];
    d += text;
    if (dest == 0x70) {
        logs[src] = d;
    }else {
        logs[src] = "";
    }
    QString time = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz");
    d = time + ": [0x" + QString::number(src, 16).toUpper() + "]" + " -> " + d;
    show_text(d, Qt::gray);
}

Dialog_log::~Dialog_log(){
    qDebug() << "~Dialog_log";
    disconnect(mc, &Controller::log_data_recved, this, &Dialog_log::log_data_recved);
    delete ui;
}

void Dialog_log::show_text(QString text, QColor c){
    ui->textEditLog->setTextColor(c);
    ui->textEditLog->insertPlainText(text+"\r\n");
    if (auto_scroll) {
        ui->textEditLog->moveCursor(QTextCursor::End);
    }
}

void Dialog_log::on_pushButton_clicked()
{
    ui->textEditLog->clear();
    ui->textEditLog->moveCursor(QTextCursor::Start);
}


void Dialog_log::on_checkBox_stateChanged(int arg1)
{
    auto_scroll = arg1 > 0;
}

